using BackData;
using Domain.DTOs.RBAC;
using Domain.RBAC;
using Infratructure;
using MediatR;
using SqlSugar;
using Team.API.Applocation.Command.Users.Departments;
using Yitter.IdGenerator;

namespace Team.API.Applocation.Handler.Users.Departments
{
    /// <summary>
    /// 创建部门处理器
    /// </summary>
    public class CreateDepartmentHandler : IRequestHandler<CreateDepartmentCommand, APIResult<DepartmentDTO>>
    {
        private readonly IRepository<Departmentmodel> departmentRepository;

        public CreateDepartmentHandler(IRepository<Departmentmodel> departmentRepository)
        {
            this.departmentRepository = departmentRepository;
        }

        public async Task<APIResult<DepartmentDTO>> Handle(CreateDepartmentCommand request, CancellationToken cancellationToken)
        {
            // 验证必填字段
            if (string.IsNullOrWhiteSpace(request.DepartmentCode) ||
                string.IsNullOrWhiteSpace(request.DepartmentName))
            {
                return APIResult<DepartmentDTO>.Faile("部门编号和名称不能为空");
            }

            var code = request.DepartmentCode.Trim();
            var name = request.DepartmentName.Trim();

            // 检查部门编号是否已存在
            bool codeExists = await departmentRepository.GetAll()
                .Where(d => d.IsDel == false && d.DepartmentCode == code)
                .AnyAsync();

            if (codeExists)
            {
                return APIResult<DepartmentDTO>.Faile("部门编号已存在");
            }

            // 检查父级部门是否存在
            int level = 1;
            string? fullPath = null;
            if (request.ParentId > 0)
            {
                var parentDept = await departmentRepository.GetByIdAsync(request.ParentId);
                if (parentDept == null || parentDept.IsDel)
                {
                    return APIResult<DepartmentDTO>.Faile("父级部门不存在");
                }
            }

            // 创建部门
            var department = new Departmentmodel
            {
                Id = YitIdHelper.NextId(),
                DepartmentCode = code,
                DepartmentName = name,
                ParentId = request.ParentId,
                Description = request.Description,
                LeaderId = request.LeaderId,
                LeaderName = request.LeaderName,
                Sort = request.Sort,
                Status = 1, // 默认启用
                Phone = request.Phone,
                Email = request.Email,
                Remark = request.Remark,
                //Createdate = DateTime.Now,
                //Createname = "系统管理员", // TODO: 从当前登录用户获取
                IsDel = false
            };

            int rows = await departmentRepository.AddAsync(department);
            if (rows <= 0)
            {
                return APIResult<DepartmentDTO>.Faile("创建部门失败");
            }

            // 构造返回DTO
            var dto = new DepartmentDTO
            {
                Id = department.Id,
                DepartmentCode = department.DepartmentCode,
                DepartmentName = department.DepartmentName,
                ParentId = department.ParentId,
                Description = department.Description,
                LeaderId = department.LeaderId,
                LeaderName = department.LeaderName,
                Sort = department.Sort,
                Status = department.Status,
                Phone = department.Phone,
                Email = department.Email,
                Remark = department.Remark,
                //CreateDate = department.Createdate,
                //CreateName = department.Createname
            };

            return APIResult<DepartmentDTO>.Ok("创建部门成功", dto);
        }
    }
}
